package com.ark.controller.admin;

import com.ark.constant.MessageConstant;
import com.ark.properties.ResourcesProperties;
import com.ark.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

import java.net.InetAddress;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Tag(name = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    private Environment env;

    @Autowired
    private ResourcesProperties resourcesProperties;

    @PostMapping("/upload")
    @Operation(summary = "文件上传")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传: {}",file.getOriginalFilename());
        String uploadDir = System.getProperty("user.dir")+resourcesProperties.getPath();
        String fileName = UUID.randomUUID()+"."+getFileExtension(file.getOriginalFilename());
        try {
            File dir = new File(uploadDir);
            if(!dir.exists()){
                dir.mkdirs();
            }
            //保存文件至本地
            Path path = Paths.get( uploadDir+fileName);
            Files.write(path,file.getBytes());
            //构建图片访问路径
            String url = "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + env.getProperty("server.port") + "/img/" + fileName;
            log.info("回显url: {}",url);
            return Result.success(url);
        }catch (Exception e){
            log.error("文件上传失败: {}",e.getMessage());
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }


    private String getFileExtension(String fileName) {
        if (fileName == null) {
            return null;
        }
        int lastIndex = fileName.lastIndexOf(".");
        if (lastIndex == -1) {
            return null;
        }
        return fileName.substring(lastIndex + 1);
    }
}
